import request from "@/utils/request.js";
import { ElMessage } from "element-plus";

export function getPersonInfo(studentId) {
  return request({
    url: `/admin/preReserve/memberInfo/${studentId}`,
    method: "GET",
  });
}

export function getExcle(studentId) {
  return request({
    url: `/admin/preReserve/personalExcelInfo/${studentId}`,
    method: "GET",
    responseType: "blob", // 确保文件是以 blob 形式返回
  })
    .then((response) => {
      // 创建一个下载链接并触发下载
      const blob = new Blob([response.data], {
        type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
      });
      const link = document.createElement("a");
      link.href = URL.createObjectURL(blob);
      link.download = "student_" + studentId + ".xlsx"; // 设置下载文件的名称
      link.click(); // 触发下载
    })
    .catch((error) => {
      console.error("请求失败:", error);
      ElMessage.error("请求失败！");
    });
}

//导出pdf
export function getPdf(data) {
  return request({
    url: "/admin/preReserve/membersPDF",
    method: "POST",
    responseType: "blob", // 确保响应类型为 blob
    data,
  })
    .then((response) => {
      const contentDisposition = response.headers["content-disposition"];
      let fileName = ""; // 默认文件名
      if (contentDisposition && contentDisposition.includes("filename=")) {
        fileName = contentDisposition.split("filename=")[1];
      }
      const url = window.URL.createObjectURL(new Blob([response.data]));
      const link = document.createElement("a");
      link.href = url;
      link.setAttribute("download", fileName); // 使用后端返回的文件名
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      ElMessage.success("导出成功！");
    })
    .catch((error) => {
      ElMessage.error("导出失败！");
      console.error("导出失败", error);
    });
}

export function updatePersonInfo(userId, preReserveInfoDTO) {
  const updateInfoDTO = {
    userId,
    preReserveInfoDTO,
  };
  return request({
    url: "/admin/preReserve/updatePersonInfo",
    method: "PUT",
    data: updateInfoDTO,
  });
}
